#include "yfy_device.h"

int infy_device_init(infy_inst_t* inst,const uint32_t* tx_id, int (*can_send_func)(infy_frame_t* frame))
{
	if (inst == NULL || can_send_func == NULL|| tx_id==NULL) {
		return -1; // Error: Invalid parameters
	}
	inst->curr = 0.0f;
	inst->volt = 0.0f;
	inst->status = 0;
	inst->can_send_func = can_send_func;
	memcpy(inst->tx_id, tx_id, TX_ID_NUM * (sizeof(uint32_t)));
	return 0; // Success
}

int infy_device_send_swtich(infy_inst_t* inst,uint8_t Switch)
{
	if (inst == NULL || inst->can_send_func == NULL) {
		return -1; // Error: Invalid instance
	}
	infy_frame_t frame = {0};
	frame.id = inst->tx_id[INFY_TX_SWITCH]; // Example ID for status message
	frame.dlc = 8;    // Data length code
	frame.data[0] = Switch;
	return inst->can_send_func(&frame);
}

int infy_device_send_voltage(infy_inst_t* inst, float curr, float volt)
{
	if (inst == NULL || inst->can_send_func == NULL) {
		return -1; // Error: Invalid instance
	}
	infy_frame_t frame = { 0 };
	frame.id = inst->tx_id[INFY_TX_CURR]; // Example ID for current message
	frame.dlc = 8;    // Data length code
	// Pack current into data bytes
	uint32_t volt_int = (uint32_t)(volt * VOLT_SCALE); // Example scaling
	uint32_t curr_int = (uint32_t)(curr * CURR_SCALE); // Example scaling
	frame.data[0] = (volt_int >> 24) & 0xFF;
	frame.data[1] = (volt_int >> 16) & 0xFF;
	frame.data[2] = (volt_int >> 8) & 0xFF;
	frame.data[3] = volt_int & 0xFF;
	frame.data[4] = (curr_int >> 24) & 0xFF;
	frame.data[5] = (curr_int >> 16) & 0xFF;
	frame.data[6] = (curr_int >> 8) & 0xFF;
	frame.data[7] = curr_int & 0xFF;
	return inst->can_send_func(&frame);
}

int infy_device_send_current(infy_inst_t* inst,float curr,float volt)
{
	if (inst == NULL || inst->can_send_func == NULL) {
		return -1; // Error: Invalid instance
	}
	infy_frame_t frame = {0};
	frame.id = inst->tx_id[INFY_TX_CURR]; // Example ID for current message
	frame.dlc = 8;    // Data length code
	// Pack current into data bytes
	uint32_t volt_int = (uint32_t)(volt * VOLT_SCALE); // Example scaling
	uint32_t curr_int = (uint32_t)(curr * CURR_SCALE); // Example scaling
	frame.data[0] = (volt_int >> 24) & 0xFF;
	frame.data[1] = (volt_int >> 16) & 0xFF;
	frame.data[2] = (volt_int >> 8) & 0xFF;
	frame.data[3] = volt_int & 0xFF;
	frame.data[4] = (curr_int >> 24) & 0xFF;
	frame.data[5] = (curr_int >> 16) & 0xFF;
	frame.data[6] = (curr_int >> 8) & 0xFF;
	frame.data[7] = curr_int & 0xFF;
	return inst->can_send_func(&frame);
}

int infy_device_send_status(infy_inst_t* inst,uint8_t status)
{
	if (inst == NULL || inst->can_send_func == NULL) {
		return -1; // Error: Invalid instance
	}
	infy_frame_t frame = {0};
	frame.id = inst->tx_id[INFY_TX_STATUS]; // Example ID for status message
	frame.dlc = 8;    // Data length code
	frame.data[0] = status;
	return inst->can_send_func(&frame);
}
